package de.g18.it0a.jlaser.jlf;

import java.text.ParseException;

import de.g18.it0a.jlaser.domain.Position;
import de.g18.it0a.jlaser.domain.Vetrine;
import de.g18.it0a.jlaser.util.StringUtil;


class JLFVetrineDefinition {

    private final int x;
    private final int y;


    private JLFVetrineDefinition(int aX, int aY) {
        x = aX;
        y = aY;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }


    public Position getPosition() {
        return new Position(getX(), getY());
    }

    @Override
    public String toString() {
        return "V" + getX() + "," + getY();
    }

    public static JLFVetrineDefinition valueOf(Position aPosition) {
        return new JLFVetrineDefinition(aPosition.getX(), aPosition.getY());
    }

    public static JLFVetrineDefinition valueOf(Vetrine aVetrine) {
        return new JLFVetrineDefinition(aVetrine.getPosition().getX(), aVetrine.getPosition().getY());
    }

    public static JLFVetrineDefinition valueOf(String aString) throws ParseException {
        String parsedString = aString;
        if (!isValidDefinition(aString)) {
            throw new ParseException(aString, 0);
        }

        parsedString = parsedString.substring(1);
        int seperatorIndex = parsedString.indexOf(",");
        if (seperatorIndex == -1) {
            throw new ParseException(aString, 1);
        }

        String x = parsedString.substring(0, parsedString.indexOf(","));
        String y = parsedString.substring(parsedString.indexOf(",") + 1, parsedString.length());
        int xOffset = StringUtil.isValidNumber(x);
        if (xOffset >= 0) {
            throw new ParseException(aString, 1 + xOffset);
        }

        int yOffset = StringUtil.isValidNumber(y);
        if (yOffset >= 0) {
            throw new ParseException(aString, aString.indexOf(',') + 1 + yOffset);
        }
        return new JLFVetrineDefinition(Integer.parseInt(x), Integer.parseInt(y));
    }

    public static boolean isValidDefinition(String aLine) {
        return aLine.startsWith("V");
    }
}